package cn.ingrun.cloud_disk.auth.authService;

import cn.ingrun.cloud_disk.model.ResponseJson;
import cn.ingrun.cloud_disk.model.User;
import cn.ingrun.cloud_disk.redis.RedisUtil;
import cn.ingrun.cloud_disk.service.UserService;
import cn.ingrun.cloud_disk.utils.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AuthServiceImpl implements AuthService {
    private Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);
    private UserService userService;
    private RedisUtil redisUtil;

    private final long tokenTime = 60 * 20;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public ResponseJson login(String id, String password) {
        User user = null;
        if (User.isEmail(id)){
            user = userService.getUserByEmail(id);
        }else if (User.isPhone(id)){
            user = userService.getUserByPhoneNumber(id);
        }else{
            return new ResponseJson(0, "用户名或密码不正确！","");
        }
        if (user == null){
            return new ResponseJson(0,"用户名或密码不正确！","");
        }

        if (!user.checkPassword(password)){
            return new ResponseJson(0,"用户名或密码不正确！","");
        }
        logger.info("用户验证成功：" + user.toString());

        String token = this.createToken(user);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        return new ResponseJson(1,"登陆成功",jsonObject);
    }

    @Override
    public ResponseJson logout(String token) {
        ResponseJson responseJson = new ResponseJson();
        if (redisUtil.del(token)){
            responseJson.setCode(1);
            responseJson.setMessage("注销成功！");
        }
        return responseJson;
    }

    @Override
    public User checkToken(String token) {
        return (User) redisUtil.getObject(token, User.class);
    }

    @Override
    public String createToken(User user) {
        String token = StringUtil.randomString(30);
        redisUtil.setObject(token, user, tokenTime);
        return token;
    }
}
